<template>
	<view class="page">
		<empty tips="非常抱歉，访问不存在" :isLoading="step !== 2"></empty>
		<empty tips="此时此刻需要您登录喔~" :isLoading="step !== 3"></empty>
		<button style="width: 30vw" v-if="step === 3" type="primary" @tap="goLogin()">去登录</button>
		<empty tips="您还没激活邀请码~" :isLoading="step !== 4"></empty>
		<component v-if="step === 1" :is="component" :info="info"></component>
		<!-- <a-video></a-video>
        <view class="b-info">
            <text class="b-name">{{info.name}}</text>
            <text class="b-desc">{{info.desc}}</text>
            <text class="b-time">{{info.createTime}}</text>
        </view>
        <view class="divider"></view> -->
		<!-- <view class="tab-">

        </view> -->
		<!-- <empty tips="暂无详情" :isLoading="false"></empty> -->
		<u-modal v-model="show" :show-confirm-button="false" content="请使用微信APP扫码打开"></u-modal>
	</view>
</template>

<script>
import ad from '@/utils/bookad.js'
import Empty from '@/components/empty'
import * as API from '../../api/book'
import Hls from '../../static/hls.js'
import { loginWxH5, getWxCode, isSubscribed, getVisitbook } from '@/api/login/index.js'

export default {
	components: {
		Empty
	},
	data() {
		return {
			step: 0,
			hasInfo: true,
			pageId: null,
			component: null,
			info: {},
			code: '',
			openid: '',
			show: false,
			needAuth: false, // 是否需要授权
			timerId: null, // 用于存储定时任务的ID
			c0: () => import('./components/page/dictionary'),
			c1: () => import('./components/page/audio'),
			c2: () => import('./components/page/video'),
			c3: () => import('./components/page/imageNode'),
			c4: () => import('./components/page/imageNodeLocal')
		}
	},
	onShow() {
		if (this.step === 3) this.getPageInfo()
		this._isSubscribed(this.openid) // 获取扫码关注状态
	},
	onLoad(options) {
		console.log('options: ', options)
		// if (options.id === 'L57dL') {
		// 测试专用id
		if (this.platform !== 'H5-WEIXIN') {
			this.show = true
			return
		}
		//不是微信回调过来的要判断下是否需要授权，已授权登录的弹窗关注 type int  1.新书、2.旧书
		API.authDetail(options.id, 1).then((res) => {
			this.needAuth = res.data.needAuth
			if (this.needAuth) {
				if (!options?.code) {
                    console.log(555555);
					const time = parseInt(localStorage.getItem('isLogin'))
					if (time < new Date().getTime() || !time) {
						this._removeLocalLogin()
						this.h5Login(options.id)
					} else if (!(options?.code && toptions?.state)) {
						const openId = localStorage.getItem('openid')
						if (openId) {
							this._getWxCode({
								code: '',
								id: options.id,
								type: 1,
								openid: openId
							})
						}
					}
				} else {
                    console.log(4444444);
						this.getStatisticsEve()
				}
			} else {
					let openId = localStorage.getItem('openid')
                console.log(33333333, openId);
					if (!openId) {
							this._removeLocalLogin()
							this.h5Login(options.id)
					} else {
							this.getStatisticsEve()
					}
			}
		})
	},
	mounted() {
		// ad.init({
		// 	imgSrc: "https://t7.baidu.com/it/u=825057118,3516313570&fm=193&f=GIF",
		// 	closeBtn: 1,
		// 	end: () => {
		// 	}
		// })
		console.log(' this.$route.query: ', this.$route.query)
		if (this.$route.query.id) {
			this.pageId = this.$route.query.id
		}
		//是从微信授权地址跳回来的去拿关注码
		if (this.$route.query?.code && this.$route.query?.state) {
			this.code = this.$route.query?.code
			// this.pageId = this.$route.query?.state
			this._getWxCode({
				code: this.code,
				id: this.pageId,
				type: 1
			})
		}

		this.getPageInfo()
	},
	methods: {
		goLogin() {
			uni.navigateTo({
				url: '/pages/login/index'
			})
		},

		isSupported() {
			return (
				Hls.isSupported || document.createElement('video').canPlayType('application/vnd.apple.mpegURL') !== ''
			)
		},
		getPageInfo() {
			if (!this.pageId) {
				this.step = 2
				return
			}
			API.detail(this.pageId, this.isSupported())
				.then((res) => {
					this.step = 1
					this.info = res.data
					window.copyText = this.info.copyText
					this.component = this['c' + this.info.tplId]
					// if (this.info.adList) {
					//     this.info.adList.forEach((res) => {
					//         ad.init(res)
					//     })
					// }
				})
				.catch((e) => {
					console.log(e)
					if (e.result.status === 401) {
						this.step = 3
					} else if (e.result.data.invalid) {
						this.step = 4
					} else {
						this.step = 2
					}
				})
		},
		h5Login(id) {
			loginWxH5({
				state: id,
				url: window.location.href
			}).then((res) => {
				console.log('res: ', res)
				window.location.href = res.data.url
			})
		},
		_getWxCode(params) {
			API.authDetail(params.id, 1).then((pan) => {
				getWxCode(params).then((res) => {
					console.log('res: ', res)
					this.openid = res.data.openid
					if (res.data.openid == null) {
						this.$navTo(
							`pages/book/detail`,
							{
								id: this.pageId,
								skip: true
							},
							'redirectTo'
						)
					}
					this._doLocalLogin(res.data.openid)
          if (!pan.data.needAuth) return
					if (res.data.adUrl) {
						ad.init({
							imgSrc: res.data.adUrl,
							textcolor: res.data.color,
							imageUrl: res.data.image_url,
							closeBtn: 1,
							end: () => {
								clearInterval(this.timerId)
								// this.$navTo(`pages/book/detail`, {
								// 	id: this.pageId,
								// 	skip: true
								// }, 'redirectTo')
							}
						})
						//定时每两秒查看是否关注，已关注就关闭弹窗并取消定时任务
						if (!this.timerId) {
							this.timerId = setInterval(() => this._isSubscribed(this.openid), 5000);
						}
					}
				})
			})
		},
		getStatisticsEve(){
			let openId = localStorage.getItem('openid')
			console.log(111111, openId);
			console.log(2222222, this.pageId);
			if (openId) {
				getVisitbook({openId: openId, id: this.pageId, type: 1}).then()
			}
		},
		_isSubscribed(openid) {
			if (openid) {
				isSubscribed({
					openid,
					bookId: this.pageId,
					type: 1
				}).then((res) => {
					if (res.data.subscribed) {
						layer.close(layer.index);
						clearInterval(this.timerId)
					}
				})
			} else {
				clearInterval(this.timerId)
			}
		},
		_doLocalLogin(openid) {
			if (openid) {
				localStorage.setItem('isLogin', new Date().getTime() + 7 * 24 * 60 * 60 * 1000)
				localStorage.setItem('openid', openid)
			}
      console.log(66666666, openid);
      this.getStatisticsEve()
		},
		_removeLocalLogin() {
			localStorage.removeItem('isLogin')
			localStorage.removeItem('openid')
		}
	},
	beforeDestroy() {
		// 在组件销毁前，确保清除定时任务
		if (this.timerId) {
			clearInterval(this.timerId)
			this.timerId = null
		}
	}
}
</script>
